//引入API文件直接进行请求
import * as api from '@/utils/api.js'
const state={
    code:'',
    token:localStorage.getItem('token'),
    userinfo:''
};
const mutations={
    SEND_CODE(state,code){
        state.code=code
    },
    SAVE_TOKEN(state,token){
        state.token=token
    },
    GETUSERINFO(state,userinfo){
        state.userinfo=userinfo
    },
    CLEAR(state){
        state.code=''
        state.token=''
        state.userinfo=''
        localStorage.removeItem('token')
    }
};
const actions={
   async sendCode({commit},phone){
        const res=await api.sendCode(phone)
        console.log(commit)
        if (res.code===200) {
            commit('SEND_CODE',res.data)
            return 'ok'
        }else{
           return Promise.reject(new Error('faile'))
        }
    },
    async register({commit},params){
        const res=await api.register(params)
        console.log(commit)
        if (res.code===200) {
            return 'ok'
        }else{
            return Promise.reject(new Error(res.message))
        } 
    },
    async login({commit},params){
        const res=await api.login(params)
        console.log(commit)
        if (res.code===200) {
            commit('SAVE_TOKEN',res.data.token)
            localStorage.setItem('token',res.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error(res.message))
        } 
    },
    async getUserInfo({commit}){
        const res=await api.getUserInfo()
        if (res.code===200) {
            commit("GETUSERINFO",res.data)
            return 'ok'
        }else{
            return Promise.reject(new Error(res.message))
        }
    },
    async logout({commit}){
        const res=await api.logout()
        if (res.code===200) {
            commit("CLEAR")
            return 'ok'
        }else{
            return Promise.reject(new Error(res.message)) 
        }
    }
};
const getters={

}
export default{
    state,
    mutations,
    actions,
    getters
}